package com.yan.project.service;

import com.yan.core.common.utils.DateUtils;
import com.yan.project.controller.EmailCodeControllerFeignClient;
import com.yan.project.mapper.TokenMapper;
import com.yan.project.mapper.UserMapper;
import com.yan.project.pojo.Token;
import com.yan.project.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;
import java.util.UUID;

/**
 * @author WangYan
 * @description:
 * @date 2021/3/15 17:27
 */
@Service
@Slf4j
public class UserService {


    @Resource
    private UserMapper userMapper;
    @Resource
    private TokenMapper tokenMapper;
    @Autowired
    private EmailCodeControllerFeignClient emailCodeControllerFeignClient;

    //是否已注册
    public Boolean isRegistered(String email) {
        long count = userMapper.count(Example.of(new User(email)));
        return count > 0;
    }

    //注册接⼝，true成功，false失败
    public Boolean register(String email, String password, String code) {
        Integer validate = emailCodeControllerFeignClient.validate(email, code);
        if (validate != 0) {
            return false;
        }
        User user = new User(email, password, 0, DateUtils.getDate(), DateUtils.getDate());
        user = userMapper.save(user);
        if (user == null || user.getId() == 0) {
            return false;
        }
        return true;
    }

    //登录接⼝
    public Boolean login(String email, String password) {
        Optional<User> one = userMapper.findOne(Example.of(new User(email)));
        //数据库查不出来
        if (one.isEmpty()) {
            return false;
        }
        User user = one.get();
        //密码错误
        if (!password.equals(user.getPassword())) {
            return false;
        }
        return true;
    }

    public String getToken(String email) {
        //登录成功生成token
        String token = UUID.randomUUID().toString();
        tokenMapper.save(new Token(email, token));
        return token;
    }

    //根据token查询⽤户登录邮箱接⼝
    public String info(String token) {
        return tokenMapper.queryLastEmail(token);
    }
}
